package com.lijian.client.controller;

import com.lijian.client.feign.AccountFeign;
import com.lijian.pojo.Admin;
import com.lijian.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;

@Controller
@RequestMapping("/account")
public class AccountClientController {

    @Autowired
    private AccountFeign accountFeign;

    @PostMapping("/login")
    public String login(@RequestParam String type, @RequestParam String username, @RequestParam String password, HttpSession session) {

        // object从其他微服务调用过来的数据，不再是普通的object，而是LinkedHashMap,
        // LinkedHashMap和user，admin没有任何继承关系，所以不能强转
        Object object = accountFeign.login(type, username, password);

        LinkedHashMap<String, Object> hashMap = (LinkedHashMap) object;
        String result = null;
        if(object == null){
            result = "login";
        } else {
            switch(type) {
                case "user":
                    User user = new User();
                    user.setId((Integer) hashMap.get("id"));
                    user.setUsername((String) hashMap.get("username"));
                    user.setPassword((String) hashMap.get("password"));
                    user.setNickname((String) hashMap.get("nickname"));
                    user.setGender((String) hashMap.get("gander"));
                    user.setAddress((String) hashMap.get("address"));
                    user.setTelephone((String) hashMap.get("telephone"));
                    session.setAttribute("user", user);
                    result = "index";
                    break;
                case "admin":
                    Admin admin = new Admin();
                    admin.setId((Integer) hashMap.get("id"));
                    admin.setUsername((String) hashMap.get("username"));
                    admin.setPassword((String) hashMap.get("password"));
                    session.setAttribute("admin", admin);
                    result = "main";
                    break;
            }
        }
        return result;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/user/login";
    }
}